import { bg_image } from "./indoorConfig.js";
import {userCarAdd,outdoorCheckDebt,getUnpaidOrder,userCarList,
tempLicenseOut,carcomeSimilar,getUnpaidOrderPortId,getTempLicenseOrder,
wechatRailPay,wechatAdvancePay,getUserInfo,portGetInfo,} from "../api/home/index.js"
import { getUrlParams } from '@/utils/str.js'
export default {
	data() {
		return {
			showOverlay:false,//弹窗
			bg_image,
			order: {},
			payInfo: {},
			plateNumber: '',
			portId: '',
			portType: 0, // 出入口类型 1|入口 2|出口
			couponList: [1, 2,3,4,5, 6],
			flagExist: false ,//是否存在已绑定车牌
			defaultPlateNumberOrder: { // 我的默认车牌
				plateNumber: '', // 车牌号
				order: null
			},
			platConfimbt:'',//车牌校验确认按钮文本显示
			platCancelbt:'',//车牌校验取消按钮文本显示
			platPopCont:'',//车牌校验弹窗内容
			platPopTitle:'',//弹窗标题
			platPopShow:false,//车牌校验弹窗显示
			options:{},//页面参数
			canshu:{},
			onReady:null,
		}
	},
	onLoad(options) {
		let query = options
		// #ifdef MP-ALIPAY
		if(uni.getStorageSync('app')) query = uni.getStorageSync('app')
		// #endif
		this.options = query
	},
	async onReady(){
		console.log("onReady=", query)
		let query = this.options
		
		// this.platPopSet(JSON.stringify(query),'确认','取消','提示')
		let q = query.q || query.qrCode || ''
		this.onReady = true
		if(q) {
			let decodeUrl = decodeURIComponent(decodeURIComponent(q))
			let canshu = getUrlParams(decodeUrl)
			this.canshu = canshu
			
			let querArr = q.split('/')
			let end = querArr[querArr.length-1] || ''
			let arr = end.split('?') || []
			let portCode = canshu.portCode || ''
			let portId = canshu.portId || ''
			if(portCode) await this.portGetInfo()
			if(portId) {
				let types = portId.split(',')
				console.log('types',types)
				this.portId = types[0]
				this.portType = types[1]
			}
			if(arr[0] == 'tempLicense') uni.navigateTo({url:`/pages/indoor/temporaryEntryce?portId=${this.portId}&portType=${this.portType}`})
			if(arr[0] == 'merchant') uni.navigateTo({url:`/pages/indoor/couponByPlate?qrcodeId=${canshu.qrcodeRecordId}`})
			if(uni.getStorageSync('app')) uni.removeStorageSync('app')
			this.fetchSomething()
		}else{
			this.fetchSomething()
		}
		
	},
	onShow() {
		console.log('onShow')
		if(this.onReady) this.fetchSomething()
		uni.setStorageSync('indoor',1)
	},
	onPullDownRefresh(){//页面下拉刷新
		this.fetchSomething()
		uni.stopPullDownRefresh();
	},
	methods: {
		async portGetInfo(){//根据出入口码获取信息
			let res = await portGetInfo({portCode:this.canshu.portCode})
			let data = res.data || {}
			this.portId = data.portId
			this.portType = data.portType
			this.fetchSomething()
			return data
		},
		//车牌提示痰喘改确定
		async platConfim(e){
			this.platPopShow = false
		},
		//车牌提示取消
		platCancel(){
			this.platPopShow = false
		},
		//车牌弹窗配置
		platPopSet(platPopCont,platConfimbt,platCancelbt,platPopTitle){
			this.platPopCont = platPopCont
			this.platConfimbt = platConfimbt
			this.platCancelbt = platCancelbt
			this.platPopShow = true
			this.platPopTitle = platPopTitle || '温馨提示'
		},
		async fetchSomething(query){
			this.getCarList()
			if (this.portId) {
				this.checkDebt()
				this._getOrderInfo()
			} else {
				// 如果不存在车场id，需要查询临时车的订单数据
				this._getTemporaryPlateNumberOrder()
			}
		},
		beforeBuyMonthCard() {
			if(!this.flagExist){
				uni.showModal({
					title: '友情提示',
					content: `暂未绑定车牌，点击下方《去绑定》进行车牌绑定`,
					confirmText: '去绑定',
					confirmColor: '#2770FE',
					showCancel: true,
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: `/pages/indoor/myCar?redirect=1`
							})
						}
					}
				})
				return false
			}
			//判断用户是否绑定手机号
			this.getUserinfo()
			
		},
		async getUserinfo(){
			let res = await getUserInfo()
			let data = res.data || {}
			uni.setStorageSync('userInfo',data)
			if (!data.phoneNumber) {
				uni.showModal({
					title: '友情提示',
					content: `暂未绑定手机号，点击下方《去绑定》进行手机号绑定`,
					confirmText: '去绑定',
					confirmColor: '#2770FE',
					showCancel: true,
					success: (res) => {
						if (res.confirm) {	
							uni.navigateTo({
								url: `/pages/indoor/bindphone?redirect=1` 
							})
						}
					}
				})
			} else {
				uni.navigateTo({
					url: `/pages/indoor/scheme`
				})
			}
		},
		showCoupon() {
			this.showOverlay = true
		},
		closeCoupon() {
			this.showOverlay = false
		},
		async checkDebt() {
			let res = await outdoorCheckDebt(this.portId)
			let data = res.data || {}
			if (data.result) {
				uni.showModal({
					title: '欠费提示',
					content: `您的车牌停车累计的欠费记录未缴清，点击下方《去缴费》进行补缴`,
					confirmText: '去缴费',
					confirmColor: '#2770FE',
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							uni.navigateTo({
								url: `/pages/indoor/arrears?mchId=${data.mchId}&plateNumber=${data.plateNumber}&portId=${this.portId},${this.portType}`
							})
						}
					}
				})
			}
		},
		async getCarList() {
			let res = await userCarList()
			let data = res.data || []
			if(data.length) {
				this.flagExist = true
				this.defaultPlateNumberOrder.plateNumber = data.filter(item => {
					return item.defaultFlag === 1
				})[0].plateNumber
				// 如果不存在车场id，表示用户不是通过扫描车场出入口码进来的，可以查询默认车牌的订单数据
				if (!this.portId) {
					this._getDefaultPlateNumberOrder()
				}
			} else {
				this.defaultPlateNumberOrder.plateNumber = ''
			}
		},
		go(url) {
			uni.navigateTo({
				url,
				events: {
					changePlate: (data) => {
						console.log("changePlate=", data)
						this.portId = null
						this.portCode = null
						this.portType = null
						this.defaultPlateNumberOrder.plateNumber = data.plate
						// 查询待支付的订单
						this._getDefaultPlateNumberOrder()
					}
				}
			})
		},
		// 监听车牌添加成功事件
		async handleSuccess(plateInfo) {
			if (!plateInfo.plateNumber || plateInfo.plateNumber.length < 7) {
				this.$u.toast('请检查车牌号是否正确');
				return
			}
			let res = await userCarAdd(plateInfo.plateNumber)
			this.getCarList()
		},
		async handlePay(order) {
			//道闸扫码支付
			if (this.portId) {
				let res = await wechatRailPay({portId:this.portId,orderId:order.id})
				this.payInfo = res.data || {}
				this.onBridgeReady()
			} else {
				let ress = await wechatAdvancePay({orderId:order.id})
				this.payInfo = ress.data || {}
				this.onBridgeReady()
			}
		},
		async onBridgeReady() {//调用支付宝支付
			let Provider =  await uni.getProvider({service: 'payment'})
			let payCanshu = {provider: Provider.provider[0] || 'wxpay',}
			payCanshu = {
				...payCanshu,
				orderInfo:this.payInfo.tradeNo,
			}
			let rePayment = await uni.requestPayment({...payCanshu});
			let flags = rePayment.errMsg == 'requestPayment:ok' && rePayment.resultCode != '6001'
			if(flags) {
				this.fetchSomething()
			}else{
				this.$u.toast('支付失败');
			}
		},
		/**
		 * 根据默认车牌号，查询订单数据
		 */
		async _getDefaultPlateNumberOrder() {
			let res = await getUnpaidOrder({ plateNumber: this.defaultPlateNumberOrder.plateNumber})
			this.defaultPlateNumberOrder.order = res.data || ''
		},
		/**
		 * 如果用户是扫码进入
		 * 如果是出口码，需要多调用一个出场接口
		 */
		async _getOrderInfo() {
			if (this.portType == 2) {
				let res = await tempLicenseOut({ portId: this.portId })
				let data = res.data
				if (!data) {
					// 如果是扫出场码，调用了临时牌出场接口，返回false后，
					let infoRes = await carcomeSimilar(this.portId)
					let infoResData = infoRes.data
					if (infoResData) {
						uni.navigateTo({
							url: `/pages/indoor/fuzzyPlateNumberQuery?portid=${this.portId}`
						})
					} else if (!infoResData) {
						this._getOrderInfoByPortId()
					}
				} else if (data) {
					this._getOrderInfoByPortId()
				}
			}
		},
		/** 
		 * 查询临时车牌的订单数据
		 */
		async _getTemporaryPlateNumberOrder() {
			let res = await getTempLicenseOrder({})
			let data = res.data || {}
			this.plateNumber = data ? data.plateNumber : ''
			this.order = data
		},
		
		/**
		 * 通过出场id，查询订单数据
		 */
		async _getOrderInfoByPortId() {
			let res = await getUnpaidOrderPortId(this.portId)
			let data = res.data || {}
			this.plateNumber = data ? data.plateNumber : ''
			this.order = data ?? {}
		}
	}
}
